import base64
import os
import time
import traceback

from flask import Blueprint, request, send_from_directory, abort, jsonify, render_template, send_file
from werkzeug.utils import secure_filename

from application import app, db
from models import AdvertiseImage

home_bp = Blueprint('home_bp', __name__)


@home_bp.route('/')
def home():
    return 'home'


@home_bp.route("/api/download/<filename>", methods=['GET'])
def download(filename):
    try:
        if os.path.isfile(os.path.join(app.config['BASE_URL'], 'upload', filename)):
            file_path = os.path.join(app.config['BASE_URL'] + '/upload', filename)
            # 返回一个文件
            # return send_file(file_path)
            return send_from_directory(app.config['BASE_URL'] + '/upload', filename, as_attachment=True)
        return 'ops2'
    except Exception as e:
        import traceback
        traceback.print_exc()
        return 'ops1'


@home_bp.route("/adv_imgs", methods=['GET'])
def get_adv_imgs():
    data = {
        'imgs': [],
        'meta': {
            'msg': 'success',
            'status': 200
        }
    }
    try:
        imgs = AdvertiseImage.query.all()
        imgs = [{
            'id': i.id,
            'text': i.text,
            'desc': i.desc,
            'url': i.img_url
        } for i in imgs]
    except Exception as e:
        data['meta']['msg'] = 'fail'
        data['meta']['status'] = 400
        return jsonify(data)
    data['imgs'] = imgs
    return jsonify(data)


@home_bp.route("/img/<filename>", methods=['GET'])
def show_img(filename):
    try:
        if os.path.isfile(os.path.join(app.config['BASE_URL'], 'upload', filename)):
            file_path = os.path.join(app.config['BASE_URL'] + '/upload', filename)
            # 返回一个文件
            return send_file(file_path)
    except Exception as e:
        import traceback
        traceback.print_exc()
        return 'ops1'


# 用于判断文件后缀
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']


@home_bp.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'GET':
        return render_template('upload_file.html')
    else:
        file_dir = os.path.join(app.config['BASE_URL'], app.config['UPLOAD_FOLDER'])
        if not os.path.exists(file_dir):
            os.makedirs(file_dir)

        f = request.files['myfile']  # 从表单的file字段获取文件，myfile为该表单的name值
        if f and allowed_file(f.filename):  # 判断是否是允许上传的文件类型
            fname = secure_filename(f.filename)
            ext = fname.rsplit('.', 1)[1]  # 获取文件后缀
            unix_time = int(time.time())
            new_filename = str(unix_time) + '.' + ext  # 修改了上传的文件名

            f.save(os.path.join(file_dir, new_filename))  # 保存文件到upload目录
            token = base64.b64encode(new_filename.encode()).decode()

            try:
                text = request.form.get('text')
                desc = request.form.get('desc')
                adv_img = AdvertiseImage(
                    text=text,
                    desc=desc,
                    img_url='http://192.168.56.1:9990/api/v1/img/' + new_filename
                )
                db.session.add(adv_img)
                db.session.commit()
            except Exception as e:
                traceback.print_exc()
                db.session.rollback()
            return jsonify({"code": 0, "errmsg": "上传成功", "token": token, "fileName": "/api/download/" + new_filename})
        else:
            return jsonify({"code": 1001, "errmsg": "上传失败"})
